//
//  CustomView.m
//  alertViewDemo
//
//  Created by 金狗 on 2019/3/13.
//  Copyright © 2019 金狗. All rights reserved.
//

#import "CustomView.h"
#import <Masonry/Masonry.h>

#define DEFAULT_ALERT_WIDTH  [UIScreen mainScreen].bounds.size.width/1.2
#define IH_DEVICE_WIDTH [UIScreen mainScreen].bounds.size.width
#define IH_DEVICE_HEIGHT [UIScreen mainScreen].bounds.size.height
#define DEFAULT_ALERT_HEIGHT 170
#define BUTTON_HEIGHT 50
#define XLSpace 10.0

#define TitleFont [UIFont systemFontOfSize:18.0f]
#define ButtonHeight  49.0f

@interface CustomView ()

@property (nonatomic, strong) UIView *alertContentView;
@property (nonatomic, strong) UIView * blackOpaqueView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *messageLabel;
@property (nonatomic, strong) UILabel *promptLabel;

@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIView *verLineView;

@property (nonatomic, strong) UIButton *cancleButton;
@property (nonatomic, strong) UIButton *sureBtnButton;
@property (nonatomic, strong) UIButton *downButton;

#pragma mark -- actionsheet

@property (nonatomic, copy) NSString *sheetTitle;
@property (nonatomic, copy) NSString *cancelButtonTitle;
@property (nonatomic, strong) NSArray *otherButtonTitles;
@property (nonatomic, copy) ActionSheetBlock actionSheetBlock;
@property (nonatomic, strong) UIView *buttonBackgroundView;

@end

@implementation CustomView

- (UIView *)alertContentView {
    if (!_alertContentView) {
        _alertContentView = [UIView new];
        _alertContentView.layer.cornerRadius = 5.0;
        _alertContentView.backgroundColor = [UIColor whiteColor];
    }
    return _alertContentView;
}
- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [UIView new];
        _lineView.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.6];
    }
    return _lineView;
}
- (UIView *)verLineView {
    if (!_verLineView) {
        _verLineView = [UIView new];
        _verLineView.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.6];
    }
    return _verLineView;
}
- (UIButton *)cancleButton {
    if (!_cancleButton) {
        _cancleButton = [UIButton new];
        _cancleButton.backgroundColor = [UIColor clearColor];
        [_cancleButton setTitleColor:[UIColor colorWithRed:144.0/255.0 green:145.0/255.0 blue:147.0/255.0 alpha:1] forState:UIControlStateNormal];
    }
    return _cancleButton;
}
- (UIButton *)sureBtnButton {
    if (!_sureBtnButton) {
        _sureBtnButton = [UIButton new];
        _sureBtnButton.backgroundColor = [UIColor clearColor];
        [_sureBtnButton setTitleColor:[UIColor colorWithRed:251.0/255.0 green:123.0/255.0 blue:0.0/255.0 alpha:1] forState:UIControlStateNormal];

    }
    return _sureBtnButton;
}
- (UIButton *)downButton {
    if (!_downButton) {
        _downButton = [UIButton new];
        _downButton.backgroundColor = [UIColor clearColor];
        [_downButton setImage:[UIImage imageNamed:@"close_icon"] forState:UIControlStateNormal];
    }
    return _downButton;
}
- (UIView *)buttonBackgroundView {
    if (!_buttonBackgroundView) {
        _buttonBackgroundView = [UIView new];
        _buttonBackgroundView.backgroundColor = [UIColor whiteColor];
    }
    return _buttonBackgroundView;
}
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.frame = [UIScreen mainScreen].bounds;
        self.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.6];
    }
    return self;
}
- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message prompt:(nullable NSString *)prompt sureBtn:(NSString *)sureTitle cancleBtn:(nullable NSString *)cancleTitle size:(int )size {
    self = [super init];
    if (self) {
        [self addSubview:self.alertContentView];
        [self.alertContentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self);
            make.centerY.equalTo(self);
            make.width.mas_equalTo(IH_DEVICE_WIDTH/1.2);
            make.height.mas_equalTo(size);
        }];
        
        if (title) {
            self.titleLabel = [self GetAdaptiveLable:CGRectMake(2*XLSpace, 2*XLSpace,IH_DEVICE_WIDTH/1.2 - 4*XLSpace, 20) AndText:title andIsTitle:YES];
            self.titleLabel.textAlignment = NSTextAlignmentCenter;
            [self.alertContentView addSubview:self.titleLabel];
            self.titleLabel.frame = CGRectMake(2*XLSpace, 2*XLSpace, IH_DEVICE_WIDTH/1.2 - 4*XLSpace, self.titleLabel.bounds.size.height);
        }
        if (message && !prompt) {
            self.messageLabel = [self GetAdaptiveLable:CGRectMake(XLSpace, CGRectGetMaxY(self.titleLabel.frame)+XLSpace, IH_DEVICE_WIDTH/1.2 - 4*XLSpace,0) AndText:message andIsTitle:NO];
            self.messageLabel.textAlignment = NSTextAlignmentCenter;
            [self.alertContentView addSubview:self.messageLabel];
            self.messageLabel.frame = CGRectMake(2*XLSpace, CGRectGetMaxY(self.titleLabel.frame)+XLSpace, DEFAULT_ALERT_WIDTH - 4*XLSpace, size - 4*XLSpace - self.titleLabel.frame.size.height - BUTTON_HEIGHT);
        }
        
        if (message && prompt) {
            self.messageLabel = [self GetAdaptiveLable:CGRectMake(XLSpace, CGRectGetMaxY(self.titleLabel.frame)+XLSpace, DEFAULT_ALERT_WIDTH - 4*XLSpace,2*XLSpace) AndText:message andIsTitle:NO];
            self.messageLabel.textAlignment = NSTextAlignmentCenter;
            [self.alertContentView addSubview:self.messageLabel];
            self.messageLabel.frame = CGRectMake(2*XLSpace, CGRectGetMaxY(self.titleLabel.frame)+XLSpace, DEFAULT_ALERT_WIDTH - 4*XLSpace, 2*XLSpace);
       
            self.promptLabel = [self GetPromptLable:CGRectMake(XLSpace, CGRectGetMaxY(self.messageLabel.frame)+XLSpace, DEFAULT_ALERT_WIDTH - 4*XLSpace,0) AndText:prompt andIsTitle:NO];
            self.promptLabel.textAlignment = NSTextAlignmentCenter;
            [self.alertContentView addSubview:self.promptLabel];
            self.promptLabel.frame = CGRectMake(2*XLSpace, CGRectGetMaxY(self.messageLabel.frame)+XLSpace, DEFAULT_ALERT_WIDTH - 4*XLSpace, size - 6*XLSpace -  self.titleLabel.frame.size.height - self.messageLabel.frame.size.height - BUTTON_HEIGHT);
            self.promptLabel.textColor = [UIColor colorWithRed:251.0/255.0 green:123.0/255.0 blue:0.0/255.0 alpha:1];
        }
        
        [self.alertContentView addSubview:self.lineView];
        [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.alertContentView).offset(0);
            make.top.equalTo(self.alertContentView.mas_bottom).offset(-BUTTON_HEIGHT);
            make.width.mas_equalTo(IH_DEVICE_WIDTH/1.2);
            make.height.mas_equalTo(0.5f);
        }];
        
        if (cancleTitle && sureTitle) {
            [self.alertContentView addSubview:self.cancleButton];
            [self.cancleButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.alertContentView).offset(0);
                make.top.equalTo(self.lineView.mas_bottom).offset(0);
                make.width.mas_equalTo(IH_DEVICE_WIDTH/1.2/2);
                make.height.mas_equalTo(BUTTON_HEIGHT);
            }];

            [self.cancleButton setTitle:cancleTitle forState:UIControlStateNormal];
            self.cancleButton.tag = 1;
            [self.cancleButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
            
            [self.alertContentView addSubview:self.verLineView];
            [self.verLineView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(IH_DEVICE_WIDTH/1.2/2);
                make.top.equalTo(self.lineView.mas_bottom).offset(0);
                make.width.mas_equalTo(0.5f);
                make.height.mas_equalTo(BUTTON_HEIGHT);
            }];
            
            [self.alertContentView addSubview:self.sureBtnButton];
            [self.sureBtnButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(IH_DEVICE_WIDTH/1.2/2);
                make.top.equalTo(self.lineView.mas_bottom).offset(0);
                make.width.mas_equalTo(IH_DEVICE_WIDTH/1.2/2);
                make.height.mas_equalTo(BUTTON_HEIGHT);
            }];
            
            [self.sureBtnButton setTitle:sureTitle forState:UIControlStateNormal];
            self.sureBtnButton.tag = 2;
            [self.sureBtnButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        //只有确定按钮
        if(sureTitle && !cancleTitle) {
            [self.alertContentView addSubview:self.sureBtnButton];
            [self.sureBtnButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.alertContentView).offset(0);
                make.top.equalTo(self.lineView.mas_bottom).offset(0);
                make.width.mas_equalTo(IH_DEVICE_WIDTH/1.2);
                make.height.mas_equalTo(BUTTON_HEIGHT);
            }];

            [self.sureBtnButton setTitle:sureTitle forState:UIControlStateNormal];
            self.sureBtnButton.tag = 2;
            [self.sureBtnButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    return self;
}
- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message {
    self = [super init];
    if (self) {
        if (title) {
            self.titleLabel = [self GetAdaptiveLable:CGRectMake(2*XLSpace, 2*XLSpace,IH_DEVICE_WIDTH/1.2 - 4*XLSpace, 20) AndText:title andIsTitle:YES];
            self.titleLabel.textAlignment = NSTextAlignmentCenter;
            [self.alertContentView addSubview:self.titleLabel];
            self.titleLabel.frame = CGRectMake(2*XLSpace, 2*XLSpace, IH_DEVICE_WIDTH/1.2 - 4*XLSpace, self.titleLabel.bounds.size.height);
        }
        
        if (message) {
            self.messageLabel = [self GetAdaptiveLable:CGRectMake(XLSpace, CGRectGetMaxY(self.titleLabel.frame)+XLSpace, IH_DEVICE_WIDTH/1.2 - 4*XLSpace,0) AndText:message andIsTitle:NO];
            self.messageLabel.textAlignment = NSTextAlignmentLeft;
            [self.alertContentView addSubview:self.messageLabel];
            self.messageLabel.frame = CGRectMake(2*XLSpace, CGRectGetMaxY(self.titleLabel.frame)+XLSpace, DEFAULT_ALERT_WIDTH - 4*XLSpace, self.messageLabel.bounds.size.height);
        }
        
        //关闭x
        [self.alertContentView addSubview:self.downButton];
        [self.downButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.alertContentView).offset(0);
            make.top.equalTo(self.alertContentView).offset(0);
            make.width.mas_equalTo(44);
            make.height.mas_equalTo(44);
        }];
        self.downButton.imageEdgeInsets = UIEdgeInsetsMake(14, 14, 14, 14);
        self.downButton.tag = 1;
        [self.downButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
        
        CGFloat alertHeight = self.messageLabel?CGRectGetMaxY(self.messageLabel.frame):CGRectGetMaxY(self.titleLabel.frame);
        [self addSubview:self.alertContentView];
        [self.alertContentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self);
            make.centerY.equalTo(self);
            make.width.mas_equalTo(IH_DEVICE_WIDTH/1.2);
            make.height.mas_equalTo(alertHeight + 2*XLSpace);
        }];
    }
    return self;
}
#pragma mark - 弹出 -
- (void)showXLAlertView {
    UIWindow *rootWindow = [UIApplication sharedApplication].keyWindow;
    [rootWindow addSubview:self];
    [self creatShowAnimation];
}
- (void)creatShowAnimation {
    self.alertContentView.layer.position = self.center;
    self.alertContentView.transform = CGAffineTransformMakeScale(0.90, 0.90);
    [UIView animateWithDuration:0.25 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
        self.alertContentView.transform = CGAffineTransformMakeScale(1.0, 1.0);
    } completion:nil];
}
- (void)dismissAlert {
    [self removeFromSuperview];
}
- (void)buttonEvent:(UIButton *)sender {
    if (sender.tag == 2) {
        if (self.resultIndex) {
            self.resultIndex(sender.tag);
        }
    }
    [self dismissAlert];
}
-(UILabel *)GetAdaptiveLable:(CGRect)rect AndText:(NSString *)contentStr andIsTitle:(BOOL)isTitle {
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:rect];
    contentLabel.textColor = THEMECOLOR_OF_TEXT_333333;
    contentLabel.numberOfLines = 0;
    contentLabel.text = contentStr;
    contentLabel.textAlignment = NSTextAlignmentCenter;
    if (isTitle) {
        contentLabel.font = [UIFont boldSystemFontOfSize:16.0];
    } else {
        contentLabel.font = [UIFont systemFontOfSize:14.0];
    }
    
    NSMutableAttributedString *mAttrStr = [[NSMutableAttributedString alloc] initWithString:contentStr];
    NSMutableParagraphStyle *mParaStyle = [[NSMutableParagraphStyle alloc] init];
    mParaStyle.lineBreakMode = NSLineBreakByCharWrapping;
    [mParaStyle setLineSpacing:3.0];
    [mAttrStr addAttribute:NSParagraphStyleAttributeName value:mParaStyle range:NSMakeRange(0,[contentStr length])];
    [contentLabel setAttributedText:mAttrStr];
    [contentLabel sizeToFit];
    
    return contentLabel;
}

- (UILabel *)GetPromptLable:(CGRect)rect AndText:(NSString *)contentStr andIsTitle:(BOOL)isTitle {
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:rect];
    contentLabel.textColor = THEMECOLOR_OF_TEXT_333333;
    contentLabel.numberOfLines = 2;
    contentLabel.text = contentStr;
    contentLabel.textAlignment = NSTextAlignmentCenter;
    if (isTitle) {
        contentLabel.font = [UIFont boldSystemFontOfSize:14.0];
    } else {
        contentLabel.font = [UIFont systemFontOfSize:13.0];
    }
    
    NSMutableAttributedString *mAttrStr = [[NSMutableAttributedString alloc] initWithString:contentStr];
    NSMutableParagraphStyle *mParaStyle = [[NSMutableParagraphStyle alloc] init];
    mParaStyle.lineBreakMode = NSLineBreakByCharWrapping;
    [mParaStyle setLineSpacing:3.0];
    [mAttrStr addAttribute:NSParagraphStyleAttributeName value:mParaStyle range:NSMakeRange(0,[contentStr length])];
    [contentLabel setAttributedText:mAttrStr];
    [contentLabel sizeToFit];
    
    return contentLabel;
}
- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
#pragma mark -- Actionsheet ----
- (instancetype)initWithTitle:(nullable NSString *)title cancelButtonTitle:(nullable NSString *)cancelButtonTitle otherButtonTitles:(nullable NSArray *)otherButtonTitles actionSheetBlock:(ActionSheetBlock) actionSheetBlock {
    self = [super init];
    if (self) {
        self.sheetTitle = title;
        self.cancelButtonTitle = cancelButtonTitle;
        NSMutableArray *contentArray = [NSMutableArray array];
        [contentArray addObjectsFromArray:otherButtonTitles];
        self.otherButtonTitles = [NSArray arrayWithArray:contentArray];
        self.actionSheetBlock = actionSheetBlock;

        [self initSubViews];
    }
    return self;
}
- (void)initSubViews {
    [self addSubview:self.buttonBackgroundView];
    self.buttonBackgroundView.frame = CGRectZero;
    
    if (self.sheetTitle) {
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0, IH_DEVICE_WIDTH, BUTTON_HEIGHT)];
        titleLabel.text = self.sheetTitle;
        titleLabel.numberOfLines = 0;
        titleLabel.textColor = [UIColor grayColor];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = [UIFont systemFontOfSize:13.0f];
        titleLabel.backgroundColor = [UIColor clearColor];
        [self.buttonBackgroundView addSubview:titleLabel];
    }
    
    for (NSInteger i = 0; i < self.otherButtonTitles.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = i;
        [button setTitle:_otherButtonTitles[i] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor whiteColor];
        button.titleLabel.font = TitleFont;
        [button setTitleColor:[UIColor colorWithRed:90.0/255.0 green:90.0/255.0 blue:90.0/255.0 alpha:1] forState:UIControlStateNormal];
     
        [button addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
        CGFloat buttonY = ButtonHeight * (i + (self.sheetTitle.length>0?1:0));
        button.frame = CGRectMake(0, buttonY, IH_DEVICE_WIDTH, ButtonHeight);
        [_buttonBackgroundView addSubview:button];
    }
    
    for (NSInteger i = 0; i < self.otherButtonTitles.count+1; i++) {
        CGFloat buttonY = ButtonHeight * (i + (self.sheetTitle.length>0?1:0));
        UIView *line = [[UIView alloc] initWithFrame:CGRectZero];
        line.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.6];
        line.frame = CGRectMake(0, buttonY, IH_DEVICE_WIDTH, 0.5f);
        [_buttonBackgroundView addSubview:line];
    }
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.tag = _otherButtonTitles.count;
    [cancelButton setTitle:_cancelButtonTitle forState:UIControlStateNormal];
    cancelButton.backgroundColor = [UIColor whiteColor];
    cancelButton.titleLabel.font = TitleFont;
    [cancelButton setTitleColor:[UIColor colorWithRed:251.0/255.0 green:123.0/255.0 blue:0.0/255.0 alpha:1]  forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
    CGFloat buttonY = ButtonHeight * (_otherButtonTitles.count + (self.sheetTitle.length>0?1:0)) + 5;
    CGFloat cancelBtnH = ButtonHeight;
    if (@available(iOS 11.0, *)) {
        cancelBtnH = cancelBtnH + [UIApplication sharedApplication].keyWindow.safeAreaInsets.bottom;
        cancelButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, [UIApplication sharedApplication].keyWindow.safeAreaInsets.bottom, 0);
    }
    cancelButton.frame = CGRectMake(0, buttonY, IH_DEVICE_WIDTH, cancelBtnH);
    [self.buttonBackgroundView addSubview:cancelButton];
    
    CGFloat height = cancelBtnH + ButtonHeight * (_otherButtonTitles.count + (self.sheetTitle.length>0?1:0)) + 5;
    self.buttonBackgroundView.frame = CGRectMake(0, IH_DEVICE_HEIGHT, IH_DEVICE_WIDTH, height);
}

- (void)didClickButton:(UIButton *)button {
    if (_delegate && [_delegate respondsToSelector:@selector(actionSheet:didClickedButtonAtIndex:)]) {
        [_delegate actionSheet:self didClickedButtonAtIndex:button.tag];
    }
    
    if (self.actionSheetBlock) {
        self.actionSheetBlock(button.tag);
    }
 
    [self dismissSheet];
}

- (void)dismissSheet {
    [self.buttonBackgroundView removeFromSuperview];
    [self removeFromSuperview];
}

#pragma mark - 弹出 -
- (void)showSheetView {
    UIWindow *rootWindow = [UIApplication sharedApplication].keyWindow;
    [rootWindow addSubview:self];
    
    [self creatShetShowAnimation];
}

- (void)creatShetShowAnimation {
    [UIView animateWithDuration:0.25 animations:^{
        self.buttonBackgroundView.transform = CGAffineTransformMakeTranslation(0, -self.buttonBackgroundView.frame.size.height);
    } completion:nil];
}

@end
